import axios from 'axios'
import { Message } from 'element-ui'
import Router from '../router/index'

import { getStorageToken } from '@/config/localUtils'
/**
 * 封装axios请求 post
 * TODO luance es6切面怎么写?每次请求时校验token
 * @param url 请求地址
 * @param data 请求参数
 * @param errorMsg 错误提示
 * @param callback 成功调用回调处理
 */
export const post = (url, data, errorMsg, callback) => {
  axios({
    url: url,
    headers: { 'Content-Type': 'application/json;charset=UTF-8'},
    data: data,
    method: 'post'
  }).then(res => {
    callback(res.data);
  }).catch(err => {
    if (err.response != undefined && err.response.status != undefined && err.response.status == 401) {
      Router.push('/')
    } else {
      Message.error(errorMsg + "异常: " + err.toString());
    }
  }
  )
}

export const postToken = (url, data, errorMsg, callback) => {
  let token = getStorageToken();
  axios({
    url: url,
    headers: { 'Content-Type': 'application/json;charset=UTF-8', 'token': token },
    data: data,
    method: 'post'
  }).then(res => {
    callback(res.data);
  }).catch(err => {
    if (err.response != undefined && err.response.status != undefined && err.response.status == 401) {
      timeOutLogin.TimeOutReLogin("你尚未登录或登录已经超时，请重新登录");
      Router.push('/login')
    } else {
      Message.error(errorMsg + "异常: " + err.toString());
    }
  }
  )
}
// 网上查找的切面
// Function.prototype.before = function (fn) {
//   console.log("qiemian")
//   var __self = this;
//   return function () {
//     console.log("qiemian")
//     fn.apply(this, arguments);
//     __self.apply(__self, arguments);
//   }
// };
